package com.moon.game.server;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.moon.game.constants.Constants;
import com.moon.game.manager.PlayerMG;
import com.moon.game.service.GiftService;
import com.moon.game.service.MissionService;
import com.moon.game.vos.PlayerVo;

public class ResetThread extends Thread {
	private static final Logger log = Logger.getLogger(ResetThread.class);
	private static final Logger resetlog = Logger.getLogger(Constants.LOG_RESET);

	public static ResetThread inst;
	private LinkedBlockingQueue<String> operaQueue = new LinkedBlockingQueue<String>();

	private ResetThread() {
	}

	public synchronized static void init() {
		if (inst == null) {
			inst = new ResetThread();
		}
	}

	/**
	 * 外部调用
	 */
	public void addPlayer(String playerId) {
		if (operaQueue.size() > 200) {
			log.warn("reset queue size:" + operaQueue.size());
		}
		operaQueue.add(playerId);
	}

	public void exec(String uid) {
		try {
			PlayerVo player = PlayerMG.instance.getPlayer(uid);
			if (player != null) {
				//TODO:重置人物
//				if (player.getDailyMissionList() != null) {
				//重置已经完成的任务
				MissionService.assignMission(player, 1);
//				}
				
				//发放每日登录礼包
				GiftService.addGift(player.getSid(), uid, Constants.DAY_GIFT_ID, 1);
			}
		} catch (Exception e) {
			resetlog.error("every day reset error:[" + uid + "] fail", e);
		}
		// 每天登录更新日志
		resetlog.info("everyday reset [" + uid + "] success!");
	}

	@Override
	public void run() {
		while (true) {
			try {
				String uid = operaQueue.poll(500, TimeUnit.MILLISECONDS);
				while (uid != null) {
					exec(uid);
					uid = operaQueue.poll();
				}
			} catch (Exception e) {
				log.error("Flush exception:", e);
			}
		}
	}

}
